<template>
  <div class="round-robin-tasks-container">
    <router-view v-if="isDetailMode" />
    <el-card v-else>
      <template #header>
        <div class="card-header">
          <h2>轮呼任务管理</h2>
          <div class="header-actions">
            <el-button type="primary" size="small" @click="refreshTasks">刷新</el-button>
          </div>
        </div>
      </template>

      <!-- 标签页：全部 / 未开始 / 进行中 / 已完成 -->
      <el-tabs v-model="activeTab" class="mb-4">
        <el-tab-pane label="全部任务" name="all">
          <div class="filter-bar">
            <el-select v-model="statusFilter" placeholder="任务状态" clearable style="width: 140px; margin-right: 8px;">
              <el-option label="pending" value="pending" />
              <el-option label="running" value="running" />
              <el-option label="completed" value="completed" />
            </el-select>
            <el-input v-model="createdByFilter" placeholder="创建人" clearable style="width: 180px; margin-right: 8px;" />
            <el-button type="primary" @click="applyFilters">筛选</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </div>
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="5" animated />
          </div>
          <div v-else-if="tasks.length === 0" class="empty-state">
            <el-empty description="暂无任务" />
          </div>
          <div v-else class="tasks-list">
            <el-table
              ref="allTableRef"
              :data="tasks"
              style="width: 100%"
              row-key="id"
              :row-style="{ height: '60px' }"
              :cell-style="{ padding: '12px 0' }"
            >
              <el-table-column prop="name" label="任务名称" min-width="180" show-overflow-tooltip />
              <el-table-column prop="customerCount" label="客户数量" width="100" />
              <el-table-column prop="createdAt" label="创建时间" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.createdAt) }}
                </template>
              </el-table-column>
              <el-table-column prop="createdBy" label="创建人" width="120" />
              <el-table-column prop="status" label="状态" width="120">
                <template #default="{ row }">
                  <el-tag :type="row.status === 'completed' ? 'success' : (row.status === 'running' ? 'warning' : 'info')">{{ row.status }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="progress" label="进度" width="160">
                <template #default="{ row }">
                  <el-progress :percentage="row.progress" :status="getProgressStatus(row.progress)" :format="() => `${row.progress}%`" />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="320" fixed="right">
                <template #default="{ row }">
                  <el-button size="small" type="primary" @click="goToTaskDetail(row)">查看详情</el-button>
                  <el-button size="small" type="success" @click="startTask(row)" :disabled="row.status !== 'pending'">开始轮呼</el-button>
                  <el-button size="small" @click="cancelTask(row)" v-if="canCancelTask(row)">取消任务</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-container">
              <el-pagination
                background
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalTasks"
                :page-size="pageSize"
                :current-page="currentPage"
                :page-sizes="[10, 20, 50, 100]"
                @size-change="handleSizeChange"
                @current-change="handleCurrentPageChange"
              />
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="未开始" name="pending">
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="5" animated />
          </div>
          <div v-else-if="tasks.length === 0" class="empty-state">
            <el-empty description="暂无未开始的轮呼任务" />
          </div>
          <div v-else class="tasks-list">
            <el-table
              ref="pendingTableRef"
              :data="tasks"
              style="width: 100%"
              row-key="id"
              :row-style="{ height: '60px' }"
              :cell-style="{ padding: '12px 0' }"
              @selection-change="handlePendingSelectionChange"
            >
              <el-table-column type="selection" width="55" />
              <el-table-column prop="name" label="任务名称" min-width="180" show-overflow-tooltip />
              <el-table-column prop="customerCount" label="客户数量" width="100" />
              <el-table-column prop="createdAt" label="创建时间" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.createdAt) }}
                </template>
              </el-table-column>
              <el-table-column prop="createdBy" label="创建人" width="120" />
              <el-table-column prop="progress" label="进度" width="160">
                <template #default="{ row }">
                  <el-progress
                    :percentage="row.progress"
                    :status="getProgressStatus(row.progress)"
                    :format="() => `${row.progress}%`"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="260" fixed="right">
                <template #default="{ row }">
                  <el-button size="small" type="primary" @click="goToTaskDetail(row)">查看详情</el-button>
                  <el-button size="small" type="success" @click="startTask(row)" :disabled="row.status !== 'pending'">开始轮呼</el-button>
                  <el-button size="small" @click="cancelTask(row)" v-if="canCancelTask(row)">取消任务</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-container">
              <el-pagination
                background
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalTasks"
                :page-size="pageSize"
                :current-page="currentPage"
                :page-sizes="[10, 20, 50, 100]"
                @size-change="handleSizeChange"
                @current-change="handleCurrentPageChange"
              />
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="进行中" name="running">
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="5" animated />
          </div>
          <div v-else-if="tasks.length === 0" class="empty-state">
            <el-empty description="暂无进行中的轮呼任务" />
          </div>
          <div v-else class="tasks-list">
            <el-table
              ref="runningTableRef"
              :data="tasks"
              style="width: 100%"
              row-key="id"
              :row-style="{ height: '60px' }"
              :cell-style="{ padding: '12px 0' }"
            >
              <el-table-column prop="name" label="任务名称" min-width="180" show-overflow-tooltip />
              <el-table-column prop="customerCount" label="客户数量" width="100" />
              <el-table-column prop="createdAt" label="创建时间" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.createdAt) }}
                </template>
              </el-table-column>
              <el-table-column prop="createdBy" label="创建人" width="120" />
              <el-table-column prop="progress" label="进度" width="160">
                <template #default="{ row }">
                  <el-progress
                    :percentage="row.progress"
                    :status="getProgressStatus(row.progress)"
                    :format="() => `${row.progress}%`"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="260" fixed="right">
                <template #default="{ row }">
                  <el-button size="small" type="primary" @click="goToTaskDetail(row)">查看详情</el-button>
                  <el-button size="small" @click="cancelTask(row)" v-if="canCancelTask(row)">取消任务</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-container">
              <el-pagination
                background
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalTasks"
                :page-size="pageSize"
                :current-page="currentPage"
                :page-sizes="[10, 20, 50, 100]"
                @size-change="handleSizeChange"
                @current-change="handleCurrentPageChange"
              />
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="已完成" name="completed">
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="5" animated />
          </div>
          <div v-if="tasks.length === 0 && !loading" class="empty-state">
            <el-empty description="暂无已完成的轮呼任务" />
          </div>
          <div v-else class="tasks-list">
            <el-table
              ref="completedTableRef"
              :data="tasks"
              style="width: 100%"
              row-key="id"
              :row-style="{ height: '60px' }"
              :cell-style="{ padding: '12px 0' }"
            >
              <el-table-column prop="name" label="任务名称" min-width="180" show-overflow-tooltip />
              <el-table-column prop="customerCount" label="客户数量" width="100" />
              <el-table-column prop="completedAt" label="完成时间" width="180">
                <template #default="{ row }">
                  {{ formatDate(row.completedAt) }}
                </template>
              </el-table-column>
              <el-table-column prop="createdBy" label="创建人" width="120" />
              <el-table-column prop="successRate" label="成功率" width="100">
                <template #default="{ row }">
                  <el-tag :type="getSuccessRateType(row.successRate)">
                    {{ row.successRate }}%
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120" fixed="right">
                <template #default="{ row }">
                  <el-button size="small" type="primary" @click="goToTaskDetail(row)">查看详情</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-container">
              <el-pagination
                background
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalTasks"
                :page-size="pageSize"
                :current-page="currentPage"
                :page-sizes="[10, 20, 50, 100]"
                @size-change="handleSizeChange"
                @current-change="handleCurrentPageChange"
              />
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

import { useRouter, useRoute } from 'vue-router'

// 响应式状态
const activeTab = ref('all')
const loading = ref(false)


// 表格引用
const pendingTableRef = ref()
const completedTableRef = ref()

// 过滤与分页状态
const statusFilter = ref<string | ''>('')
const createdByFilter = ref<string>('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalTasks = ref(0)

// 当前展示任务列表
const tasks = ref<any[]>([])

// 已移除前端搜索，改为请求端筛选

// 获取轮呼任务数据（/call/tasks/list，GET 查询参数）
const fetchTasks = async () => {
  loading.value = true
  try {
    // GET 查询参数
    const params: any = {
      page: currentPage.value,
      page_size: pageSize.value
    }
    // Tab 的状态过滤（全部不传，其他传）
    if (activeTab.value === 'pending') params.status = 'pending'
    if (activeTab.value === 'running') params.status = 'running'
    if (activeTab.value === 'completed') params.status = 'completed'
    // 筛选栏（如设置则覆盖/追加）
    if (statusFilter.value) params.status = statusFilter.value
    if (createdByFilter.value) params.created_by = createdByFilter.value

    const response = await axios.get('/call/tasks/list', { params })
    
    if (response.data) {
      const body = response.data.data || response.data
      const rawTasks = body.tasks || []
      const mapped = rawTasks.map((t: any) => {
        const total = t.total_count || 0
        const remaining = t.remaining_count ?? 0
        const progress = total > 0 ? Math.round(((total - remaining) / total) * 100) : 0
        return {
          id: t.id,
          name: t.task_name,
          customerCount: total,
          remainingCount: remaining,
          createdAt: t.created_at,
          createdBy: t.created_by,
          channel: t.channel,
          status: t.status,
          progress,
          successRate: t.success_rate ?? 0,
          completedAt: t.completed_at || ''
        }
      })

      tasks.value = mapped
      totalTasks.value = body.total || mapped.length
    } else {
      console.warn('API响应数据结构不符合预期', response.data)
      tasks.value = []
      totalTasks.value = 0
    }
  } catch (error: any) {
    console.error('获取轮呼任务失败:', error)
    ElMessage.error('获取轮呼任务失败，请稍后重试')
    tasks.value = []
    totalTasks.value = 0
  } finally {
    loading.value = false
  }
}

// 刷新任务
const refreshTasks = () => {
  fetchTasks()
  ElMessage.success('刷新成功')
}

// 基于 activeTab 的响应，避免 tab-click 取到旧值
watch(activeTab, (val) => {
  if (val === 'all') {
    statusFilter.value = ''
  } else if (val === 'pending') {
    statusFilter.value = 'pending'
  } else if (val === 'running') {
    statusFilter.value = 'running'
  } else if (val === 'completed') {
    statusFilter.value = 'completed'
  }
  currentPage.value = 1
  fetchTasks()
}, { immediate: true })

const applyFilters = () => {
  currentPage.value = 1
  fetchTasks()
}

const resetFilters = () => {
  statusFilter.value = ''
  createdByFilter.value = ''
  currentPage.value = 1
  fetchTasks()
}



// 取消任务
const cancelTask = async (task: any) => {
  ElMessageBox.confirm(
    `确定要取消任务「${task.name}」吗？取消后将无法恢复。`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await axios.post(`/call/tasks/${task.id}/cancel`)
      if (response.data && (response.data.code === 200 || response.status === 200)) {
        ElMessage.success(response.data.msg || '任务已取消')
        // 重新获取任务列表
        fetchTasks()
      } else {
        ElMessage.error(response.data?.msg || '取消任务失败')
      }
    } catch (error) {
      console.error('取消任务失败:', error)
      ElMessage.error('取消任务失败，请稍后重试')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 判断任务是否可以取消
const canCancelTask = (task: any) => {
  // 根据任务状态判断是否可以取消
  return task.status === 'running' || task.status === 'pending'
}

// 开始轮呼（/call/tasks/{task_id}/start）
const startTask = async (task: any) => {
  try {
    const resp = await axios.post(`/call/tasks/${task.id}/start`)
    if (resp.data && (resp.data.code === 200 || resp.status === 200)) {
      ElMessage.success(resp.data.msg || '启动通话任务成功')
      fetchTasks()
    } else {
      ElMessage.error(resp.data?.msg || '启动失败')
    }
  } catch (e:any) {
    ElMessage.error(e?.response?.data?.msg || '启动失败，请稍后重试')
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 获取进度条状态
const getProgressStatus = (progress: number) => {
  if (progress === 100) return 'success'
  if (progress > 50) return 'warning'
  return 'primary'
}

// 获取成功率标签类型
const getSuccessRateType = (successRate: number) => {
  if (successRate >= 80) return 'success'
  if (successRate >= 50) return 'warning'
  return 'danger'
}




// 处理分页大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchTasks()
}

// 处理当前页码变化
const handleCurrentPageChange = (current: number) => {
  currentPage.value = current
  fetchTasks()
}

// 处理待完成任务选择变化
const handlePendingSelectionChange = () => {
  // 可以在这里添加批量操作逻辑
}

// 组件挂载时获取数据
// 初始加载交由 watch(immediate) 触发，这里无需再手动调用
onMounted(() => {})

const router = useRouter()
const route = useRoute()
const isDetailMode = computed(() => route.name === 'RoundRobinTaskDetail')

const goToTaskDetail = (row: any) => {
  router.push({ name: 'RoundRobinTaskDetail', params: { id: row.id } })
}
</script>

<style scoped lang="scss">
.round-robin-tasks-container {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    h2 {
      margin: 0;
      font-size: 18px;
      font-weight: 500;
    }
  }

  .loading-container {
    padding: 20px 0;
  }

  .empty-state {
    padding: 40px 0;
    text-align: center;
  }

  .tasks-list {
    margin-top: 10px;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .task-details {
    .task-info {
      margin-bottom: 20px;
    }

    .task-customer-list {
      margin-top: 20px;
      h3 {
        margin-bottom: 10px;
        font-size: 16px;
        font-weight: 500;
      }
    }
  }
}
</style>